<template>
  <div class="insp">
    <div class="insp-total">
      <div class="insp-total-left">
        <div class="insp-total-top">
          <div class="insp-total-middle">
            <CardContainer headerName="本月养护病害类型统计">
              <template slot="card-content">
                <div class="posbox">
                  <div class="card_title">
                    <div style="padding: 2px 15px; text-align: center; z-index: 999" :class="{ card_title_select: selectTab_item === 0 }" @click="selectTab(0)">按结构</div>
                    <div style="padding: 2px 15px; text-align: center; z-index: 999" :class="{ card_title_select: selectTab_item === 1 }" @click="selectTab(1)">按桥梁</div>
                  </div>
                </div>

                <div class="card_title_list" v-show="selectTab_item === 0"><div id="typeAnalysis" class="insp-total-typeAnalysis"></div></div>
                <div class="card_title_list" v-show="selectTab_item === 1">
                  <div id="chartBar" class="chartBars"></div>
                </div>
              </template>
            </CardContainer>
          </div>
          <div class="insp-total-middle">
            <CardContainer headerName="本月养护总数分析">
              <template slot="card-content">
                <div id="sum" class="insp-total-sum"></div>
              </template>
            </CardContainer>
          </div>
        </div>
        <div class="insp-total-bottom" ref="calendarDiv">
          <el-calendar v-model="value" ref="calendar">
            <template slot="dateCell" slot-scope="{ date, data }">
              <div class="insp-calendar-slot">
                <p :class="data.isSelected ? 'is-selected' : ''">
                  <span class="insp-calendar-day">
                    {{ data.day.split('-').slice(2).join('-') }}
                  </span>
                </p>
                <div v-if="data.day.split('-')[1] === key">
                  <div v-if="calendarData[data.day.split('-').slice(2).join('-')]">
                    <div v-if="calendarData[data.day.split('-').slice(2).join('-')].length > 0">
                      <span
                        :title="calendarData[data.day.split('-').slice(2).join('-')][0]['name']"
                        :class="[
                          'insp-calendar-task',
                          { purple: calendarData[data.day.split('-').slice(2).join('-')][0]['typeStr'] === '定期养护' },
                          { green: calendarData[data.day.split('-').slice(2).join('-')][0]['typeStr'] === '日常养护' },
                          { orange: calendarData[data.day.split('-').slice(2).join('-')][0]['typeStr'] === '亮化养护' },
                        ]"
                      >
                        {{ calendarData[data.day.split('-').slice(2).join('-')][0]['name'] }}
                      </span>
                    </div>
                    <div v-if="calendarData[data.day.split('-').slice(2).join('-')].length > 1">
                      <span class="insp-calendar-more"><i class="el-icon-more"></i></span>
                      <div :class="data.isSelected ? 'insp-calendar-moreDIV' : 'insp-calendar-none'">
                        <VuePerfectScrollbar class="scroller" :settings="settings">
                          <h4>当天任务列表</h4>
                          <div class="insp-calendar-taskBox">
                            <span
                              :class="['insp-calendar-taskDiv', { purple: item.typeStr === '定期养护' }, { green: item.typeStr === '日常养护' }, { orange: item.typeStr === '亮化养护' }]"
                              @click="
                                (e) => {
                                  handleClickTask(item.id, e)
                                }
                              "
                              v-for="item in calendarData[data.day.split('-').slice(2).join('-')]"
                              :key="item.id"
                              :title="item.name"
                            >
                              {{ item['name'] }}
                            </span>
                          </div>
                        </VuePerfectScrollbar>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </el-calendar>
        </div>
      </div>
      <div class="insp-total-right">
        <CardContainer headerName="养护任务详情">
          <template slot="card-content">
            <div class="insp-total-taskDetail" v-if="taskId">
              <div class="insp-total-taskBox">
                <div class="insp-total-taskBox-header">
                  <label>养护进度</label>
                </div>
                <div class="insp-total-taskBox-content">
                  <div class="insp-total-timeLine">
                    <TimeLine :status="status"></TimeLine>
                  </div>
                </div>
              </div>
              <div class="insp-total-taskBox">
                <div class="insp-total-taskBox-header">
                  <label>养护信息</label>
                </div>
                <div class="insp-total-taskBox-content">
                  <div :class="['insp-total-taskBox-div', item['fix'] || '']" v-for="(item, index) in info" :key="index">
                    <span class="insp-total-taskBox-one">{{ item.label }} : </span>
                    <span class="insp-total-taskBox-two" :title="item.key === 'state' ? statusText(obj[item.key]) : obj[item.key] ? obj[item.key] : '未知'">{{
                      item.key === 'state' ? statusText(obj[item.key]) : obj[item.key] ? obj[item.key] : '未知'
                    }}</span>
                  </div>
                </div>
              </div>
              <div class="insp-total-taskBox insp-total-taskBox-table">
                <div class="insp-total-taskBox-header">
                  <label>病害记录</label>
                </div>
                <div class="insp-total-taskBox-content insp-total-taskBox-tableDiv" ref="tableDiv">
                  <el-table
                    :data="tableData"
                    stripe
                    :header-cell-style="{
                      color: '#999',
                      height: '44px',
                    }"
                    style="width: 100%; border: 1px solid #ebeef5; border-bottom: 0"
                    :max-height="tableHeight"
                  >
                    <el-table-column prop="bridgeName" label="桥梁名称" width="80" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="name" label="病害名称" width="80" show-overflow-tooltip></el-table-column>
                    <el-table-column property="diseaseLevel" label="病害程度" width="80" show-overflow-tooltip>
                      <template slot-scope="scope">
                        <span>
                          {{ levelText(scope.row.diseaseLevel) }}
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="diseaseLocationStr" label="病害位置" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="createTime" label="记录时间" show-overflow-tooltip></el-table-column>
                  </el-table>
                </div>
              </div>
            </div>
            <div class="insp-total-taskNoData" v-else>
              <img src="@/assets/images/pages/aliNoData.png" class="insp-total-noDataImage" />
            </div>
          </template>
        </CardContainer>
      </div>
    </div>
  </div>
</template>

<script>
import CardContainer from '@/views/healthMonitor/components/CardContainer'
import TimeLine from './timeLine'
import echarts from 'echarts'
import moment from 'moment'
import VuePerfectScrollbar from 'vue-perfect-scrollbar'
export default {
  data() {
    return {
      value: new Date(),
      year: '',
      selectTab_item: 0,
      month: '',
      day: '',
      startDate: '2021-01-16 12:00:00',
      chartBar: null,
      key: '',
      barData: [],
      taskId: null,
      tableHeight: 0,
      typeAnalysis: '',
      sum: '',
      calendarData: {},
      deaseData: [],
      totalData: {},
      status: 0,
      info: [
        {
          key: 'name',
          label: '养护名称',
        },
        {
          key: 'reportDept',
          label: '上报部门',
        },
        {
          key: 'typeStr',
          label: '养护类型',
        },
        {
          key: 'distributionPersonName',
          label: '养护员',
        },
        {
          key: 'startTime',
          label: '计划时间',
        },
        {
          key: 'state',
          label: '执行状态',
        },
        {
          key: 'maintenanceDescribe',
          label: '养护描述',
          fix: 'fix',
        },
      ],
      obj: {},
      tableData: [],
      settings: {
        // perfectscrollbar settings
        maxScrollbarLength: 30,
        wheelSpeed: 1,
        swipeEasing: true,
      },
    }
  },
  components: {
    CardContainer,
    TimeLine,
    VuePerfectScrollbar,
  },
  watch: {
    value: function (val) {
      const _date = moment(val).format('YYYY-MM-DD')
      let _dateArr = _date.split('-')
      this.year = _dateArr[0]
      this.month = parseInt(_dateArr[1], 10)
      this.key = _dateArr[1]
      this.day = _dateArr[2].toString()

      this.queryCalendar()
      this.queryDiseaseCount()

      this.queryMaintenanceCount()
      this.queryDiseaseBar()
    },
  },
  created() {
    let _date = moment(this.value).format('YYYY-MM-DD')
    let _dateArr = _date.split('-')
    this.year = _dateArr[0]
    this.month = parseInt(_dateArr[1], 10)
    this.key = _dateArr[1]
    this.day = _dateArr[2].toString()

    this.queryCalendar()
    this.queryDiseaseCount()

    this.queryMaintenanceCount()
    this.queryDiseaseBar()
  },
  mounted() {
    // 监听窗口变化
    window.addEventListener('resize', () => {
      this.typeAnalysis.resize()
      this.sum.resize()
      this.drawBarChart.resize()
      this.$nextTick(() => {
        this.$refs.calendar.$el.style.width = this.$refs.calendarDiv.offsetWidth + 'px'
        if (this.taskId) {
          this.tableHeight = this.$refs.tableDiv.offsetHeight + 'px'
        }
      })
    })
    this.$nextTick(() => {
      this.$refs.calendar.$el.style.width = this.$refs.calendarDiv.offsetWidth + 'px'
      if (this.taskId) {
        this.tableHeight = this.$refs.tableDiv.offsetHeight + 'px'
      }
    })
    this.drawBarChart()
  },
  activated() {
    let _date = moment(this.value).format('YYYY-MM-DD')
    let _dateArr = _date.split('-')
    this.year = _dateArr[0]
    this.month = parseInt(_dateArr[1], 10)
    this.key = _dateArr[1]
    this.day = _dateArr[2].toString()

    this.queryCalendar()
    this.queryDiseaseCount()

    this.queryMaintenanceCount()
    this.queryDiseaseBar()
  },
  methods: {
    drawBarChart() {
      let bgColor = '#fff',
        fontColor = '#666'
      let chartData = this.barData

      let xData = chartData.map((v) => v.name)
      let sData = chartData.map((v) => v.value)

      let lineOption = {
        lineStyle: {
          color: 'rgba(151,151,151,0.5)',
          type: 'dashed',
        },
      }

      this.chartBar = new echarts.init(document.getElementById('chartBar'))
      this.chartBar.setOption({
        backgroundColor: bgColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        grid: {
          top: '9%',
          right: '3%',
          left: '5%',
          bottom: '20%',
        },
        dataZoom: [
          {
            type: 'slider',
            show: true,
            xAxisIndex: [0],
            left: '9%',
            bottom: -20,
            height: 27.5,
            start: 10,
            end: 90, //初始化滚动条
          },
        ],
        xAxis: [
          {
            type: 'category',
            data: xData,
            axisLine: lineOption,
            axisTick: {
              show: false,
            },
            axisLabel: {
              margin: 10,
              color: fontColor,
              textStyle: {
                fontSize: 14,
              },
            },
            splitLine: {
              show: false,
            },
          },
        ],
        yAxis: [
          {
            axisLabel: {
              formatter: '{value}',
              color: fontColor,
            },
            axisTick: {
              show: false,
            },
            axisLine: lineOption,
            splitLine: {
              show: false,
            },
          },
          {
            axisLine: lineOption,
            axisTick: {
              show: false,
            },
            splitLine: {
              show: false,
            },
          },
        ],
        series: [
          {
            type: 'bar',
            data: sData,
            barWidth: '10px',
            itemStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {
                      offset: 0,
                      color: '#00BD89', // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: '#C9F9E1', // 100% 处的颜色
                    },
                  ],
                  false
                ),
              },
            },
          },
        ],
      })
    },

    selectTab(val) {
      
      this.selectTab_item = val
      
    },
    drawTypeAnalysis() {
      let _data = this.deaseData
      const _obj = this.arrayToObj(_data, 'name')
      this.typeAnalysis = new echarts.init(document.getElementById('typeAnalysis'))
      this.typeAnalysis.setOption({
        legend: {
          orient: 'vertical',
          top: 'center',
          right: '6%',
          data: ['桥面系', '上部结构', '下部结构', '其他'],
          itemWidth: 12,
          itemHeight: 10,
          itemGap: 15,
          formatter: (name) => {
            return `${name}  ${_obj[name]['value']}`
          },
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {d}%',
        },
        color: ['#56D38D', '#FF9F43', '#7467F0', '#FBE033'],
        series: [
          {
            name: '病害类型统计',
            type: 'pie',
            radius: ['0', '70%'],
            center: ['30%', '52%'],
            label: {
              show: false,
            },
            labelLine: {
              show: false,
            },
            data: _data,
          },
        ],
      })
    },
    drawSum() {
      let _data = this.totalData
      this.sum = new echarts.init(document.getElementById('sum'))
      this.sum.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        legend: {
          data: ['日常养护', '亮化养护', '定期养护'],
          right: 2,
          top: 15,
          textStyle: {
            color: '#666666',
          },
          itemWidth: 10,
          itemHeight: 10,
          itemGap: 35,
        },
        grid: {
          left: '3%',
          right: '3%',
          bottom: '20px',
          containLabel: true,
        },
        dataZoom: [
          {
            show: true,
            height: 15,
            xAxisIndex: [0],
            bottom: 0,
            start: 0,
            end: 30,
            handleSize: '110%',
            handleStyle: {
              color: '#5B3AAE',
            },
            textStyle: {
              color: 'rgba(204,187,225,0.5)',
            },
            fillerColor: 'rgba(67,55,160,0.4)',
            borderColor: 'rgba(204,187,225,0.5)',
          },
          {
            type: 'inside',
            show: true,
            height: 15,
            start: 1,
            end: 35,
          },
        ],
        xAxis: [
          {
            type: 'category',
            data: _data['xAxis'] || [],
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: '#ccc',
              },
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            axisLabel: {
              show: true,
              textStyle: {
                color: '#ccc',
              },
            },
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            splitLine: {
              show: false,
            },
          },
        ],
        series: [
          {
            name: '日常养护',
            type: 'bar',
            data: _data['0'] || [],
            barWidth: 10,
            itemStyle: {
              color: '#327BDC',
            },
          },
          {
            name: '亮化养护',
            type: 'bar',
            data: _data['1'] || [],
            barWidth: 10,
            itemStyle: {
              color: '#FF9F43',
            },
          },
          {
            name: '定期养护',
            type: 'bar',
            data: _data['2'] || [],
            barWidth: 10,
            itemStyle: {
              color: '#7467F0',
            },
          },
        ],
      })
    },
    arrayToObj(arr, key) {
      let _obj = {}
      arr.forEach((item) => {
        _obj[item[key]] = item
      })
      return _obj
    },
    queryCalendar() {
      this.$api.curing
        .queryCalendar({
          year: parseInt(this.year),
          month: parseInt(this.month),
        })
        .then((response) => {
          if (response.data.success) {
            let _obj = response.data.data
            let _newObj = {}

            Object.keys(_obj).forEach((key) => {
              let _key = ''
              if (parseInt(key) > 0 && parseInt(key) < 10) {
                _key = `0${key}`
              } else {
                _key = `${key}`
              }
              _newObj[_key] = _obj[key]
            })
            this.calendarData = _newObj
            if (_newObj[this.day] && _newObj[this.day].length > 0) {
              this.taskId = _newObj[this.day][0]['id']
              this.queryTaskById(this.taskId)
            } else {
              this.taskId = null
            }

            this.$nextTick(() => {
              this.$refs.calendar.$el.style.width = this.$refs.calendarDiv.offsetWidth + 'px'
            })
          }
        })
    },
    queryDiseaseCount() {
      this.$api.curing
        .queryDiseaseCount({
          year: parseInt(this.year),
          month: parseInt(this.month),
        })
        .then((response) => {
          
          if (response.data.success) {
            let _obj = response.data.data
            let _deaseData = []
            Object.keys(_obj).forEach((key) => {
              switch (parseInt(key)) {
                case 0:
                  _deaseData.push({
                    name: '桥面系',
                    value: parseInt(_obj[key]),
                  })
                  break
                case 1:
                  _deaseData.push({
                    name: '上部结构',
                    value: parseInt(_obj[key]),
                  })
                  break
                case 2:
                  _deaseData.push({
                    name: '下部结构',
                    value: parseInt(_obj[key]),
                  })
                  break
                case 3:
                  _deaseData.push({
                    name: '其他',
                    value: parseInt(_obj[key]),
                  })
                  break
              }
            })
           
            this.deaseData = _deaseData
            this.drawTypeAnalysis()
          }
        })
    },

    queryMaintenanceCount() {
      this.$api.curing
        .queryMaintenanceCount({
          year: parseInt(this.year),
          month: parseInt(this.month),
        })
        .then((response) => {
          if (response.data.success) {
            let _obj = response.data.data
            let _xAxis = []
            let _data0 = []
            let _data1 = []
            let _data2 = []
            Object.keys(_obj).forEach((key) => {
              _xAxis.push(`${key}号`)
              _data0.push(parseInt(_obj[key]['0']))
              _data1.push(parseInt(_obj[key]['1']))
              _data2.push(parseInt(_obj[key]['2']))
            })
            this.totalData = {
              xAxis: _xAxis,
              0: _data0,
              1: _data1,
              2: _data2,
            }
            this.drawSum()
          }
        })
    },
    queryTaskById(val) {
      this.$api.curing
        .queryTaskById({
          id: val,
        })
        .then((response) => {
          if (response.data.success) {
         
            this.status = response.data.data['state']
            this.obj = response.data.data
            this.tableData = response.data.data['diseaseVOList'] || []
            this.$nextTick(() => {
              this.tableHeight = this.$refs.tableDiv.offsetHeight + 'px'
            })
          }
        })
    },

    queryDiseaseBar() {
      this.$api.curing
        .queryDiseaseBar({
          year: parseInt(this.year),
          month: parseInt(this.month),
        })
        .then((response) => {
          if (response.data.success) {
          
            this.barData = response.data.data
            this.drawBarChart()
          }
        })
    },

    handleClickTask(val, e) {
      e = event || window.event
      e.stopPropagation()
      this.taskId = val
      this.queryTaskById(val)
    },
    statusText(type) {
      switch (type) {
        case 0:
          return '创建设施损坏情况单'
        case 1:
          return '设施管理科安排任务中'
        case 2:
          return '设施待确认(巡视大队)'
        case 3:
          return '设施确认中(巡视大队)'
        case 4:
          return '设施待确认(设施科)'
        case 5:
          return '设施确认中(设施员)'
        case 6:
          return '设施确认完成(待派维修单)'
        case 7:
          return '维修单派单中'
        case 8:
          return '施工部门待接单'
        case 9:
          return '施工部门已接单'
        case 10:
          return '施工维修中'
        case 11:
          return '施工完成'
        case 12:
          return '维修结果待核查'
        case 13:
          return '维修结果核查中'
        case 14:
          return '维修结果待确认'
        case 15:
          return '维修结果确认中'
        case 98:
          return '待发'
        case 99:
          return '处理完成'
        default:
          return ''
      }
    },
    levelText(type) {
      switch (type) {
        case 0:
          return '一级'
        case 1:
          return '二级'
        case 2:
          return '三级'
        default:
          return ''
      }
    },
  },
}
</script>
<style scoped lang="scss">
@import '@/views/inspection/insp.scss';

/deep/.el-table__header tr,
/deep/.el-table__header th {
  padding: 0;
  height: 44px;
}

/deep/.el-table td,
/deep/.el-table th {
  text-align: center;
  font-size: 14px;
}
.card_title_list {
  overflow: hidden;
}

/deep/.el-table td {
  font-weight: 400;
  color: #333;
  padding: 0;
  height: 44px;
  line-height: 44px;
}

/deep/.el-table--striped .el-table__body tr.el-table__row--striped td {
  background: #fff;
}

/deep/.el-calendar {
  height: 100%;
}

/deep/.el-calendar-table {
  border-collapse: separate;
  border-spacing: 2px 2px;
  height: 100%;
  background: #fff;
}

/deep/.el-calendar-table thead th {
  padding: 3px 0;
  font-weight: 500;
  text-align: center;
  color: #8998ac;
  background: #edf0f5;
  border-radius: 2px;
  line-height: 30px;
}

/deep/.el-calendar__body {
  padding: 5px 10px;
}

/deep/.el-calendar-table tr td {
  border: 1px solid #ebeef5 !important;
}

/deep/.el-calendar__body {
  height: calc(100% - 53px);
}

/deep/.el-calendar-table tbody {
  height: calc(100% - 50px);
}

/deep/.el-calendar-table tbody td {
  height: calc(100% / 6) !important;
}

/deep/.el-calendar-table .el-calendar-day {
  padding: 4px 8px 0;
  height: 100% !important;
}

.insp-calendar-slot {
  height: 100% !important;
  position: relative;
}

/deep/.el-calendar-table .el-calendar-day p {
  text-align: left;
}
.chartBars {
  width: 600px;
  height: 200px;
}

/deep/.el-calendar-table td.is-today {
  .insp-calendar-day {
    display: inline-block;
    width: 21px;
    height: 21px;
    background: linear-gradient(295deg, #74bbf0 0%, #327bdc 100%);
    color: #fff;
    border-radius: 50%;
    line-height: 21px;
    text-align: center;
  }
}

/deep/.el-calendar-table td.is-selected {
  .insp-calendar-day {
    display: inline-block;
    width: 21px;
    height: 21px;
    background: linear-gradient(295deg, #74bbf0 0%, #327bdc 100%);
    color: #fff;
    border-radius: 50%;
    line-height: 21px;
    text-align: center;
  }
}
.posbox {
  position: relative;
  .card_title {
    position: absolute;
    right: 5px;
    top: -40px;
    width: 148px;
    border-radius: 5px;
    text-align: center;
    display: flex;
    border: 1px solid #eee;
  }
}

.card_title_select {
  background: #5eadff;
  color: #fff;
}

.insp-calendar-task {
  display: inline-block;
  position: absolute;
  bottom: 4px;
  left: 0;
  padding-left: 8px;
  line-height: 26px;
  font-size: 12px;
  width: 100%;
  height: 26px;
  box-shadow: 0px 0px 4px 0px rgba(116, 103, 240, 0.2);
  border-radius: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}

.insp-calendar-more {
  display: inline-block;
  position: absolute;
  top: 0;
  right: 0;
  font-size: 14px;
  font-weight: bolder;
  line-height: 21px;
  cursor: pointer;
  color: #327bdc;
}

.insp-calendar-moreDIV {
  display: block;
  position: absolute;
  bottom: 0;
  right: -160px;
  width: 150px;
  height: 190px;
  z-index: 100;
  background: #fff;
  box-shadow: 0px 0px 5px 0px rgba(50, 123, 220, 0.4);
  border-radius: 4px;

  h4 {
    font-size: 13px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #8998ac;
    line-height: 30px;
    text-align: center;
    border-bottom: 1px solid #f7f7f7;
  }

  .insp-calendar-taskBox {
    height: 200px;
    overflow-y: auto;
  }

  .insp-calendar-taskDiv {
    display: block;
    margin-left: 8px;
    padding-left: 8px;
    margin-top: 5px;
    line-height: 26px;
    font-size: 12px;
    width: 126px;
    height: 26px;
    box-shadow: 0px 0px 4px 0px rgba(116, 103, 240, 0.2);
    border-radius: 2px;

    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: pointer;
  }
}

.purple {
  background: #e6e3fd;
  border-left: 3px solid #7467f0;
  color: #7467f0;
}

.green {
  background: #e7faef;
  border-left: 3px solid #2ac770;
  color: #2ac770;
}

.orange {
  background: #fee7d0;
  border-left: 3px solid #ff9f43;
  color: #ff9f43;
}

.insp-calendar-none {
  display: none;
}

.scroller {
  width: 100%;
  height: 100%;
}
</style>
